//
// Created by 崔世强 on 2018/3/25.
// Copyright (c) 2018 Facebook. All rights reserved.
//

import Foundation
import SnapKit
import Toast_Swift
import SwiftyJSON

class ModifyGroupNameController: ChatBaseController {
    
    var groupId: Int!
    var groupName: String?
    var group: Group?
    
    let groupService = GroupService()
    let msgService = ChatService()
    
    lazy var doneButtonItem: UIBarButtonItem = {
        let barItem = UIBarButtonItem(title: "完成", style: .plain, target: self, action: #selector(done))
        barItem.isEnabled = false
        return barItem
    }()
    
    lazy var textField: UITextField = {
        let textField = UITextField()
        textField.clearButtonMode = .whileEditing
        textField.adjustsFontSizeToFitWidth = true
        textField.delegate = self
        textField.text = groupName ?? ""
        textField.becomeFirstResponder()
        return textField
    }()
    
    lazy var tableView: UITableView = {
        var table = UITableView(frame: self.view.bounds, style: .grouped)
        table.delegate = self
        table.dataSource = self
//        table.backgroundColor = .clear
        return table
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.addSubview(tableView)
        self.navigationItem.title = "群聊名称"
        self.navigationItem.rightBarButtonItem = doneButtonItem
        
        tableView.snp.makeConstraints { make in
            make.edges.equalTo(self.view)
        }
        NotificationCenter.default.addObserver(self, selector: #selector(textChanged), name: UITextField.textDidChangeNotification, object: nil)
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        NotificationCenter.default.removeObserver(self)
    }
}


extension ModifyGroupNameController {
    fileprivate func onSuccess() {
        DispatchQueue.main.async {
            self.group?.name = self.groupName
            self.view.hideToastActivity()
            self.navigationController?.popViewController(animated: true)
        }
    }
    
    fileprivate func onFailure(_ msg:String) {
        DispatchQueue.main.async {
            self.view.hideToastActivity()
            self.view.makeToast(msg, position: .center)
        }
    }
    
    @objc func done() {
            self.view.makeToastActivity(.center)
            self.groupName = textField.text
            let userId = AppStatusManager.instance.userLoginStatus.1 ?? 0
            IM.request(.modifyGroupName(groupId: groupId, userId: userId, name: groupName ?? ""),success: { [unowned self] (json) in
                if reqSuccess(json["code"].stringValue) {
                    do {
                        try self.groupService.update(self.groupId, withName: self.groupName ?? "")
                    } catch {
                        print(error)
                    }
                    let dic: [String: Any] = ["type": NoticeType.modifyGroupName.rawValue, "name": self.groupName]
                    let msgJson = JSON(dic)
                    self.msgService.sendNoticeMsg(msgJson.rawString() ?? "", to: self.groupId, chatType: .group)
                    self.onSuccess()
                } else {
                    let msg = json["msg"].stringValue
                    self.onFailure(msg)
                }
                }, error: { (code) in
                    print("状态异常：\(code)")
                    self.onFailure("服务异常，请稍后再试")
            }) { (error) in
                print(error)
                self.onFailure("服务或网络异常")
            }
        
//            imApi.request(.modifyGroupName(groupId: groupId, userId: AppStatusManager.instance.userLoginStatus.1 ?? 0, name: groupName ?? "")) { result in
//                do {
//                    if case let .success(response) = result {
//                        //                        let data = try? response.mapJSON()
//                        print(String(data: response.data, encoding: .utf8))
//                        let json = JSON(response.data)
//                        if reqSuccess(json["data", "code"].stringValue) { //如果操作成功
//                            try self.groupService.update(self.groupId, withName: self.groupName ?? "")
//                            let dic: [String: Any] = ["type": NoticeType.modifyGroupName.rawValue, "name": self.groupName]
//                            let msgJson = JSON(dic)
//                            try self.msgService.sendNoticeMsg(msgJson.rawString() ?? "", to: self.groupId)
//                            self.onSuccess()
//                        } else {
//                            let msg = json["msg"].stringValue
//                           self.onFailure(msg)
//                        }
//                    } else {
//                        self.view.hideToastActivity()
//                    }
//                } catch {
//                    print(error)
//                    self.view.hideToastActivity()
//                }
//            }

    }
    
    @objc func textChanged(_ textField: UITextField) {
        let maxLength = 50
        let text = self.textField.text ?? ""
        if let selectedRange = self.textField.markedTextRange, let position = self.textField.position(from: selectedRange.start, offset: 0) {} else {
            if text.count > maxLength {
                self.textField.text = text.substring(s: 0, maxLength)
            }
        }
    }
}

extension ModifyGroupNameController: UITextFieldDelegate {
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        self.doneButtonItem.isEnabled = true
        return true
    }
    
    
}


extension ModifyGroupNameController: UITableViewDelegate, UITableViewDataSource {
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    //生成表视图单元格
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellIdentifier = "TextField"
        var cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)
        if cell == nil {
            cell = UITableViewCell(style: .default, reuseIdentifier: cellIdentifier)
            cell?.contentView.addSubview(textField)
        }
        
        //        cell?.isUserInteractionEnabled = false
        textField.snp.makeConstraints { make in
            make.left.equalTo(cell!.contentView).offset(20)
            make.right.equalTo(cell!.contentView).offset(-20)
            make.center.equalTo(cell!.contentView)
        }
        return cell!
    }
    
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return "群聊名称"
    }
    
    //获取分组数量
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
}
